import { Effect, Reducer } from 'umi'

import { UserService } from '@/services'
import { IBaseResp } from '@/utils/types'
import { IUserLoginResponse } from '@/services/user/types'
import { BASE_AVATAR_SRC } from '@/constants'

export interface IUserModelState {
  isLogin: boolean
  userInfo: {
    username: string
    token: string
    avatarSrc?: string
  } | null
}

export interface IUserModel {
  namespace: 'user'
  state: IUserModelState
  effects: {
    loginEffect: Effect
    loginWithTokenEffect: Effect
    logoutEffect: Effect
  }
  reducers: {
    login: Reducer<IUserModelState>
    logout: Reducer<IUserModelState>
  }
}

const userModel: IUserModel = {
  namespace: 'user',
  state: {
    isLogin: false,
    userInfo: null
  },
  effects: {
    // 手动登录
    *loginEffect({ payload, callback }, { call, put }) {
      // 执行异步函数
      try {
        const res: IUserLoginResponse = yield call(() => UserService.login(payload))
        if (res) {
          callback && callback(res)
          yield put({
            type: 'login',
            payload: res
          })
        }
      } catch (error) {
        console.log('接口请求失败', error)
      }
    },
    // token 登录
    *loginWithTokenEffect({ payload, callback }, { call, put }) {
      try {
        const res: IUserLoginResponse = yield call(() =>
          UserService.loginWithToken(null, { noNotification: true })
        )
        //手动判断业务逻辑
        if (res) {
          callback && callback(res)
          yield put({
            type: 'login',
            payload: res
          })
        } else {
          yield put({
            type: 'logout'
          })
        }
      } catch (error) {
        console.log('接口请求失败', error)
      }
    },
    *logoutEffect({ payload, callback }, { call, put }) {
      // try {
      //   const res: IBaseResp = yield call(() => UserService.logout(null, { noNotification: true }))
      //   if (res.code === 200) {
      //     callback && callback(res)
      //     localStorage.removeItem('token')
      //     localStorage.removeItem('username')
      //     yield put({
      //       type: 'logout',
      //       payload: res
      //     })
      //   }
      // } catch (error) {
      //   console.log('接口请求失败', error)
      // }
      yield put({
        type: 'logout'
        // payload: payload
      })
    }
  },
  reducers: {
    login(state, action) {
      return {
        ...state,
        isLogin: true,
        userInfo: {
          username: action?.payload?.username || action?.payload?.data?.username,
          token: localStorage.token,
          avatarSrc: action?.payload?.userInfo?.avatarSrc || BASE_AVATAR_SRC
        }
      }
    },
    logout(state) {
      return {
        ...state,
        isLogin: false,
        userInfo: null
      }
    }
  }
}

export default userModel
